<template>
  <ElFormItem class="fa-table-setting__fields">
    <template #label>
      <span>表格项设置</span>
      <a v-if="addible" class="field-setting-btn add-button el-icon-plus" @click="add"></a>
    </template>

    <DragSort
      class="fa-widget-setting__option-list field-list"
      :list="fields"
      :disabled="disabled"
      handle
      @drop="onDrop"
    >
      <DragSortItem
        v-for="(item, index) in fields"
        :key="item.id || index"
        :index="index"
        class="field-item"
        :class="{ 'is-active': activeIndex === index }"
      >
        <div class="field-item__hd" @click="activeIndex = activeIndex === index ? -1 : index">
          <div class="field-item__hd--left">
            <span class="field-item__hd-text" :title="item.label || `表格项${index + 1}`">{{
              item.label || `表格项${index + 1}`
            }}</span>

            <a class="field-setting-btn field-item__arrow el-icon-caret-right"></a>
          </div>

          <a v-if="removable" class="field-setting-btn fa-icon-delete" @click.stop="data.removeTableField(index)"></a>
        </div>

        <ElCollapseTransition>
          <div class="field-item__bd" v-show="activeIndex === index">
            <ElFormItem :prop="`tableFields[${index}].label`" :rules="getFieldRule(index)">
              <ElInput
                class="field-item__input"
                v-model="item.label"
                clearable
                placeholder="请输入表头名称"
                :maxlength="config.fieldLabelMaxLength"
                :disabled="disabled"
                @blur="item.label = item.label.trim()"
              />
            </ElFormItem>

            <ElFormItem label="提示文本">
              <ElInput
                class="field-item__input"
                v-model="item.placeholder"
                clearable
                placeholder="请输入提示文本"
                :maxlength="config.fieldPlaceholderMaxLength"
                :disabled="disabled"
                @blur="item.placeholder = item.placeholder.trim()"
              />
            </ElFormItem>

            <ElFormItem>
              <ElCheckbox v-model="item.required" :disabled="disabled">必填</ElCheckbox>
            </ElFormItem>
          </div>
        </ElCollapseTransition>
      </DragSortItem>
    </DragSort>
  </ElFormItem>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, onMounted, toRef } from 'vue'
import { Widget } from '@/models'
import config from '@/config'
import { scrollIntoView } from '@/utils'
import { useFieldActiveIndex } from './utils'
import DragSort from '@/components/drag-sort/DragSort.vue'
import DragSortItem from '@/components/drag-sort/DragSortItem.vue'

export default defineComponent({
  name: 'TableSettingFields',

  components: { DragSort, DragSortItem },

  props: {
    /** 控件数据 */
    data: {
      type: Widget,
      required: true
    },

    /** 是否禁用 */
    disabled: {
      type: Boolean,
      default: false
    }
  },

  setup(props) {
    /** 表格配置 */
    const tableConfig = config.tableOption

    /** 表格项 */
    const fields = computed(() => props.data.tableFields)

    /** 当前激活表格项 index */
    const activeIndex = useFieldActiveIndex(toRef(props, 'data'))

    onMounted(() => (activeIndex.value = 0))

    return {
      /** 表格配置 */
      config: tableConfig,

      /** 表格项 */
      fields,

      /** 当前激活表格项 index */
      activeIndex,

      /** 是否可新增表格项 */
      addible: computed(() => {
        const { data: widget, disabled } = props

        return !disabled && fields.value.length < (widget.isHorizontalTable ? widget.tableColsMax : widget.tableRowsMax)
      }),

      /** 新增字段 */
      async add() {
        props.data.addTableField()

        await nextTick()

        // 滚动到最后一个
        scrollIntoView('.fa-widget-setting .field-item:last-child')
      },

      /** 是否可删除表格项 */
      removable: computed(() => !props.disabled && fields.value.length > 1),

      /** 排序拖入 */
      onDrop({ dragIndex, dropIndex }: { dragIndex: number; dropIndex: number }) {
        // 如果拖动项原来展开则保持展开
        if (activeIndex.value === dragIndex) {
          activeIndex.value = dropIndex
        }
      },

      /** 字段校验规则 */
      getFieldRule(index: number) {
        return {
          required: true,

          validator(rule: object, value: string, callback: (e?: Error) => void) {
            if (!value) return callback(new Error(`请输入表头名称`))

            callback()
          },

          trigger: 'blur'
        }
      }
    }
  }
})
</script>

<style lang="scss">
$fieldHdHeight: 32px;

.fa-table-setting__fields {
  .el-form-item__label {
    justify-content: space-between;
    padding-right: 0;
  }

  .fa-drag-sort-item {
    &__handle {
      height: $fieldHdHeight;
      margin-left: -8px;
      line-height: $fieldHdHeight;
    }

    &__content {
      display: block;
    }
  }

  .field-setting-btn {
    margin-left: 4px;
    color: $color-text-placeholder;
    font-size: 14px;
    cursor: pointer;
    user-select: none;

    &:hover {
      color: $color-primary;
    }
  }

  .add-button {
    color: $color-text-primary;

    &.is-disabled {
      color: $color-text-disabled;
      cursor: not-allowed;
    }
  }

  .field-list {
    max-height: 32px * 5 + 160px;
  }

  .field-item {
    align-items: flex-start;
    margin: 0 -8px;
    padding: 0 8px;
    border-radius: 2px;

    &.is-active {
      background-color: $background-color-regular;

      .field-item__arrow {
        transform: rotate(90deg);
        transition: transform 0.3s ease-in-out;
      }
    }

    &:hover {
      background-color: $background-color-regular;
    }

    &__arrow {
      color: $color-info;
    }

    &__hd {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: $fieldHdHeight;

      &--left {
        display: flex;
        flex: 1 1 0px;
        align-items: center;
        width: 0;
        overflow: hidden;
      }

      &-text {
        @include text-ellipsis;
      }
    }

    .el-form-item {
      margin-bottom: 4px;
    }
  }
}
</style>
